package com.itheima.datastructure.binarysearchtree.binarytree;

import java.util.LinkedList;
import java.util.Queue;

public class E06Leetcode111_2 {
    /*
    利用层序遍历寻找最小深度：找到最先的叶子节点
     */
    public int minDepth(TreeNode root){
        if(root==null){
            return 0;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        int depth=0;//记录深度
        while(!queue.isEmpty()){
            int size= queue.size();
            depth++;
            for(int i=0;i<size;i++){
                TreeNode poll=queue.poll();
                //锁定叶子节点
                if(poll.left==null && poll.right==null){
                    return depth;
                }
                if(poll.left!=null){
                    queue.offer(poll.left);
                }
                if(poll.right!=null){
                    queue.offer(poll.right);
                }
            }
        }
        return depth;
    }
}
